package com.xgj.ph.servlet;

import com.alibaba.fastjson.JSON;
import com.xgj.ph.dao.UserDao;
import com.xgj.ph.dao.impl.UserDaoImpl;
import com.xgj.ph.entity.User;
import com.xgj.ph.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //  1.设置编码方式
        //  2.处理请求信息
        String username = req.getParameter("username");
        String pwd = req.getParameter("pwd");
        String op = req.getParameter("op");
       if(op.equals("login")){
           //  3.连接数据库，操作
           UserDao userDao = new UserDaoImpl();
           User user = userDao.selectByUsernameAndPwd(username, pwd);
           //  4.响应
           if (user != null) {      // 登录成功
               Result result = Result.success("登录成功！");
               resp.getWriter().write(JSON.toJSONString(result));

               req.getSession().setAttribute("user", user);
           }else{                  //  登录失败
               Result success = Result.error("登录失败！");
               resp.getWriter().write(JSON.toJSONString(success));
               req.getSession().setAttribute("user", null);
           }
       }else if(op.equals("register")){
            UserDao userDao = new UserDaoImpl();
            int num = userDao.insertUser(username,pwd);
           //  4.响应
           if (num == 0) {      // 注册失败
               Result result = Result.error("注册失败！");
               resp.getWriter().write(JSON.toJSONString(result));
           }else{                  //  注册成功
               Result success = Result.success("注册成功！");
               resp.getWriter().write(JSON.toJSONString(success));
           }
       }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
